package pbx.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pbx.model.Sip;


@Stateless
public class ExtenService {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Sip getById(Integer id){	
		return (Sip) em.find(Sip.class, id);
	}	

	@SuppressWarnings("unchecked")
    public List<Sip> list(int first, int max) {    	
    	Query query = em.createNamedQuery("Exten.getAll");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
        
    public Sip add(Sip exten) {
    	em.persist(exten); 
    	return exten;
    }
        
    public Sip update(Sip exten) {
    	em.merge(exten);
    	return exten;   
    }
        
    public void delete(Integer id) {
    	em.remove(em.find(Sip.class, id));	
    }
    
    //----------------------------------------------------------------------
    
	public Sip getByAccountcode(String accountcode){	
		Sip result = null;
		Query query = em.createNamedQuery("Exten.getByAccountcode");
		query.setParameter("accountcode", accountcode);
		try {
			result = (Sip) query.getSingleResult(); 
        }
    	catch (Exception e) {
			e.printStackTrace();
		}
        return result;
	}
	
	
}

